package tech.wetech.admin3.util;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import tech.wetech.admin3.sys.exception.AooUserException;

import java.util.HashMap;
import java.util.Map;

@Component
public class SendMessage {
  private static String appcode;
  private static String template_id;
  private static String host;

  @Value("${aliyun.sms.appcode}")
  public void setAppcode(String appcode) {
    SendMessage.appcode = appcode;
  }

  @Value("${aliyun.sms.template_id}")
  public void setTemplate_id(String template_id) {
    SendMessage.template_id = template_id;
  }

  @Value("${aliyun.sms.host}")
  public void setHost(String host) {
    SendMessage.host = host;
  }

  public static boolean send(String phone, String code) {
    String path = "/data/send_sms";
    String method = "POST";
    Map<String, String> headers = new HashMap<String, String>();
    //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
    headers.put("Authorization", "APPCODE " + appcode);
    //根据API的要求，定义相对应的Content-Type
    headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    Map<String, String> querys = new HashMap<String, String>();
    Map<String, String> bodys = new HashMap<String, String>();
    bodys.put("content", "code:" + code);
    bodys.put("template_id", template_id);  //该模板为调试接口专用，短信下发有受限制，调试成功后请联系客服报备专属模板
    bodys.put("phone_number", phone);
//'X-Ca-Error-Message: Invalid AppCode `not exists`'

    try {
      /**
       * 重要提示如下:
       * HttpUtils请从
       * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
       * 下载
       *
       * 相应的依赖请参照
       * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
       */
      HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
      System.out.println("发送短信验证码---打印结果---" + response.toString());
//      //获取response的body
//      System.out.println(EntityUtils.toString(response.getEntity()));
      if (response.getStatusLine().getStatusCode() == 200) {
        return true;
      } else {
        Header errorMessageHeader = response.getFirstHeader("X-Ca-Error-Message");
        if (errorMessageHeader != null) {
          String errorMessage = errorMessageHeader.getValue();
          throw new AooUserException(errorMessage);
        } else {
          throw new AooUserException("Unknown error");
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      throw new AooUserException(e.getMessage());
    }
  }
}
